﻿require 'Qt4'
load 'ui_targeteditform.rb'


class TargetEditor < Qt::MainWindow
	attr_accessor :ui
	attr_accessor :db
	attr_accessor :view_slice # Part of targets, who is viewed
	attr_accessor :view_tasks_slice # Task slice data
	attr_accessor :root_index
	attr_accessor :show_all_targets
	attr_accessor :show_all_tasks
	
	slots 'addNewTarget()','removeTarget()','targetChanged(int,int,int,int)'
	slots 'targetNameChanged()','targetStatusChanged(int)','toggleSeeAllTargets()'
	slots 'checkDayLoadCorrectness()','generateSpentTimeStatistics()','showSubtargetOfTarget()'
	
	slots 'addTask()','removeTask()','toggleSeeAllTasks()'
	slots 'taskNameChanged()','taskNoticeChanged()','taskStatusChanged(int)'
	slots 'taskExecutionDateChanged(QDate)','taskExecutionTimeChanged(QTime)'
	slots 'taskChanged(int,int,int,int)'
	
	
	def init(db, root)
		@ui=Ui_EditTargetsForm.new
        @ui.setupUi(self)
		
		@ui.dateStatsTo.setDate(Qt::Date::currentDate())
		@ui.dateStatsFrom.setDate(Qt::Date::currentDate().addDays(-14))
		
		@ui.tblSubtargets.setColumnCount(2)		
		@ui.tblSubtargets.setHorizontalHeaderLabels(['Имя','Статус'])
		@ui.tblSubtargets.horizontalHeader().resizeSection(0,325);
		@ui.tblSubtargets.horizontalHeader().resizeSection(1,80);
		
		@ui.tblTasks.setColumnCount(5)
		@ui.tblTasks.setHorizontalHeaderLabels(['Имя','Дата','Время','Потрачено','Статус'])
		
		@ui.tblTasks.horizontalHeader().resizeSection(0,124);
		@ui.tblTasks.horizontalHeader().resizeSection(1,70);
		@ui.tblTasks.horizontalHeader().resizeSection(2,65);
	    @ui.tblTasks.horizontalHeader().resizeSection(3,65);
		@ui.tblTasks.horizontalHeader().resizeSection(4,80);
		
		@db=db
		@root_index=root
		
		@show_all_targets=false
		@show_all_tasks=false
		# Get slice of targets
		@view_slice=@db.getSubtargets(root,@show_all_targets)
		@view_slice.each {   |x|
		  self.insertRowForTarget(@ui.tblSubtargets.rowCount(),x)
		}
		# Get slice of tasks
		@view_tasks_slice=@db.getTasks(root,@show_all_tasks)
		@view_tasks_slice.each {   |x|
		  self.insertRowForTask(@ui.tblTasks.rowCount(),x)
		}
		
		Qt::Object.connect(@ui.btnAddTarget,SIGNAL("clicked()"),self,SLOT("addNewTarget()"))
		Qt::Object.connect(@ui.btnRemoveTarget,SIGNAL("clicked()"),self,SLOT("removeTarget()"))
		Qt::Object.connect(@ui.tblSubtargets,SIGNAL("currentCellChanged(int,int,int,int)"),self,SLOT("targetChanged(int,int,int,int)"))
		Qt::Object.connect(@ui.txtTargetName,SIGNAL("editingFinished()"),self,SLOT("targetNameChanged()"))
		Qt::Object.connect(@ui.chkTargetCompleted,SIGNAL("stateChanged(int)"),self,SLOT("targetStatusChanged(int)"))
		Qt::Object.connect(@ui.btnSeeAllTargets,SIGNAL("clicked()"),self,SLOT("toggleSeeAllTargets()"))
		
		# TODO: Implement these slots
		Qt::Object.connect(@ui.btnCheckDays,SIGNAL("clicked()"),self,SLOT("checkDayLoadCorrectness()"))
		Qt::Object.connect(@ui.btnEditStats,SIGNAL("clicked()"),self,SLOT("generateSpentTimeStatistics()"))
		Qt::Object.connect(@ui.btnViewSubtargets,SIGNAL("clicked()"),self,SLOT("showSubtargetOfTarget()"))

		#TODO: Implement these task slots
		Qt::Object.connect(@ui.btnAddTask,SIGNAL("clicked()"),self,SLOT("addTask()"))
		Qt::Object.connect(@ui.btnRemoveTask,SIGNAL("clicked()"),self,SLOT("removeTask()"))
		Qt::Object.connect(@ui.btnSeeAllTasks,SIGNAL("clicked()"),self,SLOT("toggleSeeAllTasks()"))
		Qt::Object.connect(@ui.txtTaskName,SIGNAL("editingFinished()"),self,SLOT("taskNameChanged()"))
		Qt::Object.connect(@ui.txtTaskNotice,SIGNAL("textChanged()"),self,SLOT("taskNoticeChanged()"))
		Qt::Object.connect(@ui.chkTaskCompleted,SIGNAL("stateChanged(int)"),self,SLOT("taskStatusChanged(int)"))
		Qt::Object.connect(@ui.dateTask,SIGNAL("dateChanged(QDate)"),self,SLOT("taskExecutionDateChanged(QDate)"))
		Qt::Object.connect(@ui.timeTask,SIGNAL("timeChanged(QTime)"),self,SLOT("taskExecutionTimeChanged(QTime)"))
		Qt::Object.connect(@ui.tblTasks,SIGNAL("currentCellChanged(int,int,int,int)"),self,SLOT("taskChanged(int,int,int,int)"))
		
		self.show()
		
	end

	def addNewTarget()
		target=@db.createNewTarget(@root_index)
		@view_slice<<target
		
		insertRowForTarget(@ui.tblSubtargets.rowCount(),target)
	end
	
	def removeTarget()
		row=@ui.tblSubtargets.currentRow()
		if row!=-1
			@db.deleteTarget( @view_slice[row].getID() )
			#print "Attempting to clear selection\n"
			@ui.tblSubtargets.clearSelection()
			#print "Selection is cleared\n"
			@view_slice.delete_at(row)
			@ui.tblSubtargets.removeRow(row)
			if row<@ui.tblSubtargets.rowCount()
				#print "Attempting to set row\n"
				@ui.tblSubtargets.setCurrentCell(row,0)
				#print "Row is set\n"
			end
		end
	end
	
    def insertRowForTarget(index,target)
	    @ui.tblSubtargets.insertRow(index)
		self.updateRowTarget(index,target)
	end	
	def updateRowTarget(index,target)
		@ui.tblSubtargets.setItem(index,0,Qt::TableWidgetItem.new(target.getName()))
		
		statusString="Не выполнено";
		if (target.getStatus()==false)
			statusString="Выполнено";
		end
		@ui.tblSubtargets.setItem(index,1,Qt::TableWidgetItem.new(statusString))
	end
	
	def  insertRowForTask(index,task)
		@ui.tblTasks.insertRow(index)
		self.updateRowTask(index,task)
	end
	
	
	def  updateTaskStatus(index,status)
		statusString="Не выполнено";
		if (status==false)
			statusString="Выполнено";
		end
		@ui.tblTasks.setItem(index,4,Qt::TableWidgetItem.new(statusString))
	end
	
	def  updateRowTask(index,task)
		@ui.tblTasks.setItem(index,0,Qt::TableWidgetItem.new(task.getName()))
		@ui.tblTasks.setItem(index,1,Qt::TableWidgetItem.new(task.getExecutionDate().toString()))
		@ui.tblTasks.setItem(index,2,Qt::TableWidgetItem.new(task.getExecutionTime().toString()))
		@ui.tblTasks.setItem(index,3,Qt::TableWidgetItem.new(task.getSpentTime().toString()))
		statusString="Не выполнено";
		if (task.getStatus()==false)
			statusString="Выполнено";
		end
		@ui.tblTasks.setItem(index,4,Qt::TableWidgetItem.new(statusString))
	end
	
	def targetChanged(currentRow,currentColumn,previousRow,previousColumn)
		if currentRow!=-1
		    if currentRow >= @view_slice.count()
				return
			end
			#print "Target changed to "
			#print  currentRow
			#print "\n"
			#print @view_slice
			target=@view_slice[currentRow]
			@ui.txtTargetName.setText(target.getName())
			if target.getStatus()==true
				@ui.chkTargetCompleted.setCheckState(Qt::Unchecked)
			else
				@ui.chkTargetCompleted.setCheckState(Qt::Checked)
			end
		end
	end
	
	def targetNameChanged()
		currentRow=@ui.tblSubtargets.currentRow()
		if currentRow!=-1
			target=@view_slice[currentRow]
			target.setName(@ui.txtTargetName.text())
			updateRowTarget(currentRow,target)
		end
	end
	
	def targetStatusChanged(new_status)
		currentRow=@ui.tblSubtargets.currentRow()
		if currentRow!=-1
		    target=@view_slice[currentRow]
			# If new status of item is unechecked 
			if new_status==2
			    target.setStatus(false)	
			    if @show_all_targets==true
				    updateRowTarget(currentRow,target)
			    else
					@view_slice.delete_at(currentRow)
			        @ui.tblSubtargets.removeRow(currentRow)
				    if currentRow<@ui.tblSubtargets.rowCount()
						@ui.tblSubtargets.setCurrentCell(currentRow,0)
				    end
			    end
			else
			    target.setStatus(true)
			    updateRowTarget(currentRow,target)
			end
		end
	end
	
	def toggleSeeAllTargets()
		currentRow=@ui.tblSubtargets.currentRow()
		@ui.tblSubtargets.clearContents()
		@ui.tblSubtargets.setRowCount(0)
		
		@show_all_targets = (not @show_all_targets)
		
		newButtonLabel="Отображать всё"
		if @show_all_targets == true
			newButtonLabel="Только невып."
		end
		@ui.btnSeeAllTargets.setText(newButtonLabel)
		
		@view_slice=@db.getSubtargets(@root_index,@show_all_targets)
		@view_slice.each {   |x|
		  self.insertRowForTarget(@ui.tblSubtargets.rowCount(),x)
		}
		
		if (currentRow!=-1) and (currentRow<@ui.tblSubtargets.rowCount())
			@ui.tblSubtargets.setCurrentCell(currentRow,0)
		end
	end
	# Check, whether tasks on day are not higher than free hours
	def checkDayLoadCorrectness()
	    dates=Array.new
		@view_tasks_slice.each{ |x|
		   index=dates.index{ |j| j==x.getExecutionDate() }
		   if (index == nil)
		     dates << x.getExecutionDate()
		   end
		}
		
		correct=true
		string = "Ошибка: время было превышено\n"
		dates.each{ |x|
			total_time=@db.getTotalExecutionTimeForADay(x)
			# Get free hours
			free_hours=@db.getWeeklyFreeHours().getFreeHours(x)
			if (total_time>free_hours)
			  string=string + "\""
			  string=string + x.toString().force_encoding('UTF-8')
			  string=string + "\" cвободное время было превышено на "
			  string=string +((total_time-free_hours)/3600).to_s 
			  string=string + "ч\n"
			  correct=false
			end
		}
		if correct==true
		   Qt::MessageBox::information(self,"Ошибок не найдено","Ошибок не найдено")
		else
		   Qt::MessageBox::critical(self,"Ошибка",string)
		end
	end
	# Generates a statistics for time wasted for this subtargets task by range
	def generateSpentTimeStatistics()
		currentRow=@ui.tblSubtargets.currentRow()
		if currentRow!=-1
			from=@ui.dateStatsFrom.date()
			to=@ui.dateStatsTo.date()
			f=File.open("spent_time.csv","wt")
			# Write header
			f.write("Отчёт по выполненной работе с ")
			f.write(from.toString())
			f.write(" по ")
			f.write(to.toString())
			f.write(";\n")
			range=DTConversions::qdateToDate(from)..DTConversions::qdateToDate(to)
			string_list=Array.new
			time=@db.getSpentHoursAndWriteTarget(@view_slice[currentRow].getID(),string_list,range)
			string_list.insert(0,"Итого:;"+DTConversions::totalTimeToString(time)+";\n")
			string_list.each {|x| f.write(x)}
			f.close()
		end
	end
	# Shows all subtargets of selected target in separated window
	def showSubtargetOfTarget()
		currentRow=@ui.tblSubtargets.currentRow()
		if currentRow!=-1
			target=@view_slice[currentRow]
			ed=TargetEditor.new(self)
			ed.init(@db,target.getID())
			ed.setWindowTitle(target.getName())
		end
	end
	
	def addTask()
		task=@db.createNewTask(@root_index)
		@view_tasks_slice<<task
		
		insertRowForTask(@ui.tblTasks.rowCount(),task)
	end
	def removeTask()
		row=@ui.tblTasks.currentRow()
		if row!=-1
			@db.deleteTask( @view_tasks_slice[row].getID() )
			#print "Attempting to clear selection\n"
			@ui.tblTasks.clearSelection()
			#print "Selection is cleared\n"
			@view_tasks_slice.delete_at(row)
			@ui.tblTasks.removeRow(row)
			if row<@ui.tblTasks.rowCount()
				#print "Attempting to set row\n"
				@ui.tblTasks.setCurrentCell(row,0)
				#print "Row is set\n"
			end
		end
	end
	def toggleSeeAllTasks()
		currentRow=@ui.tblTasks.currentRow()
		@ui.tblTasks.clearContents()
		@ui.tblTasks.setRowCount(0)
		
		@show_all_tasks = (not @show_all_tasks)
		
		newButtonLabel="Отображать всё"
		if @show_all_tasks == true
			newButtonLabel="Только невып."
		end
		@ui.btnSeeAllTasks.setText(newButtonLabel)
		
		@view_tasks_slice=@db.getTasks(@root_index,@show_all_tasks)
		@view_tasks_slice.each {   |x|
		  self.insertRowForTask(@ui.tblTasks.rowCount(),x)
		}
		
		if (currentRow!=-1) and (currentRow<@ui.tblTasks.rowCount())
			@ui.tblTasks.setCurrentCell(currentRow,0)
		end
	end
	def taskNameChanged()
		currentRow=@ui.tblTasks.currentRow()
		if currentRow!=-1
			task=@view_tasks_slice[currentRow]
			task.setName(@ui.txtTaskName.text())
			updateRowTask(currentRow,task)
		end
	end
	def taskNoticeChanged()
		currentRow=@ui.tblTasks.currentRow()
		if currentRow!=-1
			task=@view_tasks_slice[currentRow]
			task.setNotice(@ui.txtTaskNotice.plainText())
			updateRowTask(currentRow,task)
		end
	end
	def taskStatusChanged(new_status)
		currentRow=@ui.tblTasks.currentRow()
		if currentRow!=-1
		    task=@view_tasks_slice[currentRow]
			# If new status of item is unechecked 
			if new_status==2
			    task.setStatus(false)	
			    if @show_all_tasks==true
				    updateRowTask(currentRow,task)
			    else
					@view_tasks_slice.delete_at(currentRow)
			        @ui.tblTasks.removeRow(currentRow)
				    if currentRow<@ui.tblTasks.rowCount()
						@ui.tblTasks.setCurrentCell(currentRow,0)
				    end
			    end
			else
			    task.setStatus(true)
			    updateRowTask(currentRow,task)
			end
		end
	end
	def taskExecutionDateChanged(new_date)
		currentRow=@ui.tblTasks.currentRow()
		if currentRow!=-1
			task=@view_tasks_slice[currentRow]
			task.setExecutionDate(@ui.dateTask.date())
			updateRowTask(currentRow,task)
		end
	end
	def taskExecutionTimeChanged(new_time)
		currentRow=@ui.tblTasks.currentRow()
		if currentRow!=-1
			task=@view_tasks_slice[currentRow]
			task.setExecutionTime(@ui.timeTask.time())
			updateRowTask(currentRow,task)
		end
	end
	def taskChanged(currentRow,currentColumn,previousRow,previousColumn)
		if currentRow!=-1
		    if currentRow >= @view_tasks_slice.count()
				return
			end
			task=@view_tasks_slice[currentRow]
			@ui.txtTaskName.setText(task.getName())
			@ui.txtTaskNotice.setPlainText(task.getNotice())
			@ui.dateTask.setDate(task.getExecutionDate())
			@ui.timeTask.setTime(task.getExecutionTime())
			
			if task.getStatus()==true
				@ui.chkTaskCompleted.setCheckState(Qt::Unchecked)
			else
				@ui.chkTaskCompleted.setCheckState(Qt::Checked)
			end
		end
	end
end